//
//  DepartmentViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/10.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

struct Department: HandyJSON {
    var id: String?
    var name: String?
    var introduction: String?
}

struct DepartmentViewModel {
    let models: [Department]
    
    var numberOfRows: Int { return models.count }
    
    func viewModel(for indexPath: IndexPath) -> RowViewModel {
        return RowViewModel(model: models[indexPath.item])
    }
    
    func viewModelForRegistration(for indexPath: IndexPath) -> RowViewModel {
        return RowViewModel(model: models[indexPath.row])
    }
    
    struct RowViewModel {
        let model: Department
        
        var departmentId: String { return model.id ?? "" }
        
        var departmentName: String { return model.name ?? "" }
        
        var departmentDesc: String { return model.introduction ?? "" }
        
        func itemHeight(with itemWidth: CGFloat) -> CGFloat {
            return departmentName.height(font: UIFont.regular(14), width: itemWidth) + 10
        }
    }
}

extension DepartmentViewModel {
    static func getDepartmentList(department: String = "",
                                  parentId: String = "",
                                  level: String = "1",
                                  success: @escaping (_ models: [Department]) -> Void,
                                  failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras = ["name": department,
                     "parentId" : parentId,
                     "level" : level]
        HttpTool.shared.request(target: ApiManager.departmentList(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<Department>.deserializeModelArrayFrom(json: json["data"].description) as? [Department] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍候重试!")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
}


